package com.xy_pro.xymanager.exception;


import com.xy_pro.xymanager.auth.dto.ResultErrorCode;
import com.xy_pro.xymanager.auth.dto.ResultResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<?> handleAuthenticationException(AuthenticationException ex) {
        logger.error("======handleAuthenticationException {}", ex.getMessage());

        logger.error("Access denied: {}", ex.getMessage());
        ResultResponse<?> error = ResultResponse.error(
                HttpStatus.FORBIDDEN.value(),
                ex.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)  // 明确设置 HTTP 状态码
                .body(error);                 // 自动设置 Content-Type 为 application/json
    }

    @ExceptionHandler(PasswordNotModifiedException.class)
    public ResponseEntity<?> handlePasswordNotModifiedException(PasswordNotModifiedException ex) {
        logger.error("======handlePasswordNotModifiedException");
//        return ResultResponse.error(HttpStatus.FORBIDDEN.value(), ex.getMessage());
        ResultResponse<?> error = ResultResponse.error(
                HttpStatus.FORBIDDEN.value(),
                ex.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)  // 明确设置 HTTP 状态码
                .body(error);
//        return ResultResponse.forbidden(ex.getMessage());
    }

    @ExceptionHandler(PasswordMismatchException.class)
    public ResponseEntity<?> handlePasswordMismatchException(PasswordMismatchException ex) {
        logger.error("======handlePasswordMismatchException {}", ex.getMessage());
        ResultResponse<?> error = ResultResponse.error(
                HttpStatus.FORBIDDEN.value(),
                ex.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)  // 明确设置 HTTP 状态码
                .body(error);
    }

    @ExceptionHandler(ServerException.class)
    public ResponseEntity<?> handleServerException(ServerException ex) {
        logger.error("======handleServerException");
        ResultResponse<?> error = ResultResponse.error(
                ResultErrorCode.ErrorServerInternal,
                ex.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)  // 明确设置 HTTP 状态码
                .body(error);
    }

    @ExceptionHandler(PhoneUserNotFoundException.class)
    public ResponseEntity<?> handlePhoneUserNotFoundException(PhoneUserNotFoundException ex) {
        logger.error("======handlePhoneUserNotFoundException {}", ex.getMessage());
        ResultResponse<?> error = ResultResponse.error(
                ResultErrorCode.ErrorPhoneNotFound,
                ex.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)  // 明确设置 HTTP 状态码
                .body(error);
    }

    @ExceptionHandler(UserInfoInValidateException.class)
    public ResponseEntity<?> handleUsernameExistsException(UserInfoInValidateException e) {
        logger.error("======handleUsernameExistsException {}", e.getMessage());
        ResultResponse<?> error = ResultResponse.error(
                HttpStatus.CONFLICT.value(),
                e.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.CONFLICT)  // 明确设置 HTTP 状态码
                .body(error);
//        return ResultResponse.error(HttpStatus.CONFLICT.value(), e.getMessage());
    } 

    @ExceptionHandler(ExcelProcessingException.class)
    public ResponseEntity<?> handleExcelProcessingException(ExcelProcessingException e) {
        logger.error("======handleExcelProcessingException {}", e.getMessage());

        ResultResponse<?> error = ResultResponse.error(
                HttpStatus.CONFLICT.value(),
                e.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.CONFLICT)  // 明确设置 HTTP 状态码
                .body(error);
//        return ResultResponse.error(HttpStatus.CONFLICT.value(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResultResponse<?> handleAllException(Exception e) {
        System.err.println("===== 全局异常捕获 =====");
        e.printStackTrace();  // 打印完整异常堆栈
        return ResultResponse.error(500, "服务器内部错误: " + e.getMessage());
    }

    // 确保捕获 JSON 解析错误
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResultResponse<?> handleJsonError(HttpMessageNotReadableException e) {
        System.err.println("===== JSON 解析错误 =====");
        e.printStackTrace();
        return ResultResponse.error(400, "JSON 解析错误: " + e.getMessage());
    }


    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<?> handleAccessDeniedException(AccessDeniedException ex) {
        logger.error("======handleAccessDeniedException: {}", ex.getMessage());
        ResultResponse<?> error = ResultResponse.error(
                HttpStatus.FORBIDDEN.value(),
                ex.getMessage()
        );
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)  // 明确设置 HTTP 状态码
                .body(error);
//        return ResultResponse.error(HttpStatus.FORBIDDEN.value(), ex.getMessage());
    }
}
